package com.example.demo.Controller;

import com.example.demo.Component.Interceptor;
import com.example.demo.Component.Salt_Encryption;
import com.example.demo.Component.Score;
import com.example.demo.Mapper.UserMapper;
//import com.sun.deploy.nativesandbox.comm.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.Info.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private Score score;
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/register")
    public boolean register(user_info userInfo){
        userInfo.setPassword(Salt_Encryption.salt_first(userInfo.getPassword()));
        int result=userMapper.register(userInfo);
        if (result>0){
            return true;
        }else {
            return false;
        }
    }
    @RequestMapping("/login")
    public boolean login(HttpServletRequest request, user_info userInfo){
        user_info user_info=userMapper.login(userInfo.getUsername());
        String final_password=user_info.getPassword();
        String input_password=userInfo.getPassword();
        if (Salt_Encryption.verify(input_password,final_password)){
            HttpSession session= request.getSession(true);
            session.setAttribute("user",user_info);
            return true;
        }else {
            return false;
        }
    }
    @RequestMapping("/userInfo")
    public user_info userinfo(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        String username=((user_info)session.getAttribute("user")).getUsername();
        user_info userInfo=(user_info) session.getAttribute("user");
        int score_count=(int)score.final_score(userInfo,"yes");
        user_info userInfo1=userMapper.userinfo(username);
        userInfo1.setUnique(score_count);
        return userInfo1;
    }
    @RequestMapping("/player")
    public List<user_info> player(HttpServletRequest request){
        user_info userInfo=(user_info) request.getSession(false).getAttribute("user");
        return (List<user_info>)score.final_score(userInfo,"no");
    }
    @RequestMapping("/log_out")
    public int log_out(HttpServletRequest request) throws IOException {
        HttpSession session=request.getSession(false);
        if (session!=null){
            session.invalidate();
            return 1;
        }
        return -1;
    }
}
